package com.flower.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.flower.domain.entity.Favorite;
import com.flower.domain.entity.Product;
import com.flower.domain.vo.buyer.FavoriteVO;
import com.flower.mapper.FavoriteMapper;
import com.flower.mapper.ProductMapper;
import com.flower.service.FavoriteService;
import com.flower.utils.UserContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author 86178
* @description 针对表【favorite(收藏夹表)】的数据库操作Service实现
* @createDate 2025-03-04 12:26:59
*/
@Service
public class FavoriteServiceImpl extends ServiceImpl<FavoriteMapper, Favorite>
    implements FavoriteService {

    @Autowired
    private ProductMapper productMapper;

    @Override
    public Page<FavoriteVO> getFavorites(Integer page, Integer pageSize) {
        // 1. 获取用户收藏列表
        LambdaQueryWrapper<Favorite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Favorite::getBuyerId, UserContext.getUserId())
              .orderByDesc(Favorite::getCreateTime);

        Page<Favorite> favoritePage = this.page(new Page<>(page, pageSize), wrapper);

        // 2. 获取商品信息
        List<Integer> productIds = favoritePage.getRecords().stream()
                .map(Favorite::getProductId)
                .collect(Collectors.toList());

        // 如果没有收藏商品，直接返回空列表，避免SQL错误
        final Map<Integer, Product> productMap;
        if (!productIds.isEmpty()) {
            List<Product> products = productMapper.selectBatchIds(productIds);
            productMap = products.stream()
                    .collect(Collectors.toMap(Product::getProductId, product -> product));
        } else {
            productMap = Collections.emptyMap();
        }

        // 3. 组装VO
        List<FavoriteVO> favoriteVOs = favoritePage.getRecords().stream().map(favorite -> {
            FavoriteVO vo = new FavoriteVO();
            BeanUtils.copyProperties(favorite, vo);

            // 设置商品信息
            Product product = productMap.get(favorite.getProductId());
            if (product != null) {
                vo.setProductName(product.getProductName());
                vo.setProductImage(product.getImage());
                vo.setPrice(product.getPrice().doubleValue() / 100);
                vo.setStock(product.getStock());
            }

            return vo;
        }).collect(Collectors.toList());

        // 4. 构建返回结果
        Page<FavoriteVO> result = new Page<>();
        BeanUtils.copyProperties(favoritePage, result, "records");
        result.setRecords(favoriteVOs);

        return result;
    }

    @Override
    public void addFavorite(Integer productId) {
        // 1. 检查是否已收藏
        if (checkFavorite(productId)) {
            return;
        }

        // 2. 添加收藏记录
        Favorite favorite = new Favorite();
        favorite.setBuyerId(UserContext.getUserId().intValue());
        favorite.setProductId(productId);
        favorite.setCreateTime(LocalDateTime.now());

        this.save(favorite);
    }

    @Override
    public void removeFavorite(Integer favoriteId) {
        // 1. 检查是否是自己的收藏
        LambdaQueryWrapper<Favorite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Favorite::getFavoriteId, favoriteId)
              .eq(Favorite::getBuyerId, UserContext.getUserId());

        this.remove(wrapper);
    }
    
    @Override
    public void removeFavoriteByProductId(Integer productId) {
        // 根据商品ID和用户ID删除收藏记录
        LambdaQueryWrapper<Favorite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Favorite::getProductId, productId)
              .eq(Favorite::getBuyerId, UserContext.getUserId());

        this.remove(wrapper);
    }

    @Override
    public boolean checkFavorite(Integer productId) {
        LambdaQueryWrapper<Favorite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Favorite::getProductId, productId)
              .eq(Favorite::getBuyerId, UserContext.getUserId());

        return this.count(wrapper) > 0;
    }
    
    @Override
    public FavoriteVO getFavoriteByProductId(Integer productId) {
        // 1. 查询收藏记录
        LambdaQueryWrapper<Favorite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Favorite::getProductId, productId)
              .eq(Favorite::getBuyerId, UserContext.getUserId());
        
        Favorite favorite = this.getOne(wrapper);
        if (favorite == null) {
            return null;
        }
        
        // 2. 查询商品信息
        Product product = productMapper.selectById(productId);
        if (product == null) {
            return null;
        }
        
        // 3. 组装VO
        FavoriteVO vo = new FavoriteVO();
        BeanUtils.copyProperties(favorite, vo);
        vo.setProductName(product.getProductName());
        vo.setProductImage(product.getImage());
        vo.setPrice(product.getPrice().doubleValue() / 100);
        vo.setStock(product.getStock());
        
        return vo;
    }
}




